# -*- coding: UTF-8 -*-

##########################################################################
#
#   Copyright (c) 2020  Bresee, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###########################################################################

### Template generation and management

from flask import Blueprint
from flask import request
import utils.pgsql.pgtemplate as template
import utils.pgsql.pgactivity as activity
import utils.common.log as log
from utils.wraps import token, urlcost
import utils.message.response as response
import utils.common.initres as initres
import utils.common.httpclient as httpclient
import json
from ast import literal_eval
import os
#import main.MyOss as oss
import requests


import utils.pgsql.pgdevice as device

if initres.COS_TYPE :
    import utils.oss.cos as oss   
else :
    import utils.oss.oss as oss


template_module = Blueprint(
    "base_template", __name__, url_prefix="/api/v1/mission/template"
)


def filterVidoes(videos: list, bgm: str):
     
    dic = {}

    videoList = []
    for video in videos:
        if video != "_":
            if "https" in video:
                videoList.append(video)

    # 保存bgm
    if bgm != "":
        if "https" in bgm:
            dic["bgm"] = bgm

    dic["videos"] = videoList
    return dic

def selsct_template_syn(dic):
    """
    模板数据同步
    查询数据库修改状态
    :return: 
    """
    # 查询 模板数据库中未同步数据
    obj = template.PgTemplate()
    caseId_str = dic.get("caseId","")
    if caseId_str:
        template_syn_data = obj.select_template_onecaseID_notsyn(caseId_str)
    else:
        template_syn_data = obj.select_template_notsyn()
    print("template_syn_data：",template_syn_data)

    # 根据模板名称  查询 活动名称  - 获取设备列表中的 设备编码  -- 查询设备所在 groupid
    for one_template_dict in template_syn_data:
        Activity_obj =activity.PgActivity()
        templateName = one_template_dict.get("templateName")

        videoConfigList_dic = Activity_obj.templateName_select_videoConfigList(templateName)
        print("videoConfigList_dic",type(videoConfigList_dic),videoConfigList_dic) # dict
        # 判断查询结果是否存在
        if not videoConfigList_dic:

            return videoConfigList_dic
        else:
            GBcode = videoConfigList_dic.get("videoConfigList",{}).get("VideoCfg")[0].get("DeviceIds")[0]

            print("GBcode",GBcode)
            # 根据 GBcode 查询 groupid
            device_obj = device.PgDevice()
            #
            groupld_str = device_obj.GBcode_select_groupld(GBcode)
            print("groupld_str",groupld_str)

            one_template_dict["groupld"] = groupld_str.get("groupld","")


    return template_syn_data

@template_module.route("/", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def template_all_admin():
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    print("userInfo",userInfo)
    obj = template.PgTemplate()
     
    if userInfo["role"] == 1:
        res = obj.all()
        for i in range(len(res)):
            res[i]["templateData"] = literal_eval(res[i]["templateData"])
        return response.make_response_success(res)
    elif userInfo["role"] == 2:
        operatorId = userInfo["operatorId"]
        res = obj.allByOperatorId(operatorId)
        for i in range(len(res)):
            res[i]["templateData"] = literal_eval(res[i]["templateData"])
        return response.make_response_success(res)
    elif userInfo["role"] == 3:
        caseId = userInfo["caseId"]
        playground_limit = userInfo["playground_limit"]
        res = obj.allByCaseId(caseId)
        filter_res = []
        for i in range(len(res)):
            res[i]["templateData"] = literal_eval(res[i]["templateData"])
            if playground_limit in res[i]['templateName']:
                filter_res.append(res[i])
        return response.make_response_success(filter_res)
    else:
        return response.make_response_401()


 
@template_module.route("/templateall", methods=["GET"])
@urlcost.cost_count_wraps
def template_all():
  

    obj = template.PgTemplate()
    res = obj.all()
    for i in range(len(res)):
        res[i]["templateData"] = literal_eval(res[i]["templateData"])
    if(res):
        return response.make_response_success(res)
    else:
        return response.make_response_1000()


 
@template_module.route("/case/templateall/<int:caseId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def template_case_all(caseId):
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    obj = template.PgTemplate()
    playground_limit = userInfo["playground_limit"] if userInfo['role'] == 3 else ""
    res = obj.allByCaseId(caseId, playground_limit)
    for i in range(len(res)):
        res[i]["templateData"] = literal_eval(res[i]["templateData"])
        res[i]["play_point"] = res[i]["templateName"].split('_')[1]
    if(res):
        return response.make_response_success(res)
    else:
        #返回空数组
        return response.make_response_success([])
        # return response.make_response_1000()

@template_module.route("/ticketPrice/templateId/<int:templateId>", methods=["GET"])
@urlcost.cost_count_wraps
def template_ticketPrice(templateId):
    res ={}
    obj = template.PgTemplate()
    template_dic = obj.get_templateId_data(templateId)

    # print("template_dic",type(template_dic),template_dic)
    if isinstance(template_dic, dict):
        ticketPrice_int = template_dic.get("ticketPrice",'')
        res["ticketPrice"] = ticketPrice_int
        res["discountPrice"] = template_dic.get("discountPrice",'')
        res["discountTime"] = template_dic.get("discountTime",'')

        return response.make_response_success(res)
    else:
        return response.make_response_1000()



@template_module.route("/", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def template_add():
    
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in [1,2, 3]:  
        dic = json.loads(request.data)
        print(dic)
        obj = template.PgTemplate()
        # 校验景区id下是否有 同名模板
        if obj.templateNameget(dic["templateName"], dic["caseId"]) != []:
            return response.make_response_1505()

        templDic = filterVidoes(
            dic["templateData"]["VideoTemplate"], dic["templateData"]["BgmPath"]
        )

        templateCloudId = "this is local id"

        dbDic = {
            "templateCloudId": templateCloudId,
            "operatorId": dic["operatorId"],
            "caseId": dic["caseId"],
            "templateName": dic["templateName"],
            "faceNum": dic["faceNum"],
            "templateData": dic["templateData"],
            "bgmName": dic["bgmName"],
            "note": dic["note"],
            "ticketPrice": dic["ticketPrice"],
            "discountPrice": dic["discountPrice"],
            "discountTime": dic["discountTime"],
        }

        res = obj.addTemplate(dbDic)

        if res:
            return response.make_response_success(res)
        else:
            return response.make_response_3101()
    else:
        return response.make_response_401()


@template_module.route("/<int:templateId>", methods=["PUT"])
@token.login_required
@urlcost.cost_count_wraps
def device_put(templateId):
  
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in[1,2, 3]:
        dic = json.loads(request.data)
        obj = template.PgTemplate()
        if (
            obj.templateNameeditget(dic["templateName"], dic["caseId"], templateId)
            != []
        ):
            return response.make_response_1505()
        templateCloudId = "this is local id"

        dbDic = {
            "templateCloudId": templateCloudId,
            "operatorId": dic["operatorId"],
            "caseId": dic["caseId"],
            "templateName": dic["templateName"],
            "faceNum": dic["faceNum"],
            "templateData": dic["templateData"],
            "bgmName": dic["bgmName"],
            "note": dic["note"],
            "ticketPrice": dic["ticketPrice"],
            "discountPrice": dic["discountPrice"],
            "discountTime": dic["discountTime"],
        }

        if obj.templatmodify(templateId, dbDic):
            return response.make_response_success_no_data()
        else:
            return response.make_response_1000()
    else:
        return response.make_response_401()


@template_module.route("/case/<int:caseId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def template_get_case(caseId):
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    if userInfo["role"] in [1, 2, 3]:
        obj = template.PgTemplate()
        res = obj.allByCaseId(caseId)
        for i in range(len(res)):
            res[i]["templateData"] = literal_eval(res[i]["templateData"])
        return response.make_response_success(res)
    else:
        return response.make_response_401()


@template_module.route("/active/<int:templateId>", methods=["GET"])
@token.login_required
@urlcost.cost_count_wraps
def template_get_active(templateId):
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])
    if userInfo["role"] in [1,2, 3]:
        activityobj = activity.PgActivity()
        return response.make_response_success(
            activityobj.get_activityName(templateId)[1]
        )
    else:
        return response.make_response_401()

#
@template_module.route("/templateUpload", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def templateone_Upload():

    dic = json.loads(request.data)
    print(dic)
    for i in dic:
        if os.path.exists(i.split(".com")[1]): # 判断文件是否存在
            os.remove(i.split(".com")[1])
            os.remove(i.split(".com")[1].split(".")[0][:-1]+ ".mp4")
            print("文件路径",i.split(".com")[1][1:])
            oss.upload_template(i.split(".com")[1][1:])
    return response.make_response_success_no_data()


@template_module.route("/templateDelete", methods=["POST"])
@token.login_required
@urlcost.cost_count_wraps
def templateone_delete():

    dic = json.loads(request.data)
    print(dic)
    for i in dic:

        if os.path.exists(i.split(".com")[1]):
            os.remove(i.split(".com")[1])
            os.remove(i.split(".com")[1].split(".")[0][:-1]+ ".mp4")
            oss.delete_template(i.split(".com")[1][1:])
    return response.make_response_success_no_data()


@template_module.route("/<int:templateId>", methods=["DELETE"])
@token.login_required
@urlcost.cost_count_wraps
def template_delete(templateId):
 
    userInfo = token.getUserInfoFromAuth(request.headers["Authorization"])

    obj = template.PgTemplate()
    activityobj = activity.PgActivity()
    if userInfo["role"] in [1,2, 3]:
        activityList = activityobj.get_activityName(templateId)[1]
        activityNameList = []
        if len(activityList) > 0:
            for file in range(len(activityList)):
                activityNameList.append(activityList[file]["activityName"])
            return {"code": 201, "activityNameList": activityNameList}
        else:
            if obj.delete(templateId):
                return response.make_response_success_no_data()
    else:
        return response.make_response_401()



@template_module.route("/template_syn", methods=["POST"])

def template_syn():
    """
    根据景区查询模板 以及 groupid
    :return: 
    """
    dic = json.loads(request.data)
    template_syn_daic = selsct_template_syn(dic)
    if template_syn_daic:
        return response.make_response_success(template_syn_daic)
    else:
        return response.make_response_405()








